﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace NiconicoAPI {
    internal class WebLogic {
        public static string HttpPost(string url, string parameters, CookieContainer cc) {
            // Requestを作成           
            var data = Encoding.ASCII.GetBytes(parameters);
            var req = (HttpWebRequest)WebRequest.Create(url);
            req.CookieContainer = cc;
            req.ContentType = "application/x-www-form-urlencoded";
            req.ContentLength = data.Length;
            req.Method = "Post";

            // POST送信
            try {
                var reqStream = req.GetRequestStream();
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            catch (WebException e) {
                if (e.Status == WebExceptionStatus.NameResolutionFailure) {
                    throw new MyException("ネットワーク接続エラー: ネットワークに繋がっていない可能性があります", e);
                }
                else {
                    throw new MyException("ネットワーク接続エラー", e);
                }
            }

            // Responseを受け取る    
            var res = req.GetResponse();
            var resStream = res.GetResponseStream();
            var sr = new StreamReader(resStream, Encoding.UTF8);
            var result = sr.ReadToEnd();
            resStream.Close();

            return result;
        }

        public static string HttpGet(string url, CookieContainer cc) {
            var req = (HttpWebRequest)WebRequest.Create(url);
            req.CookieContainer = cc;

            var res = req.GetResponse();
            var resStream = res.GetResponseStream();
            var sr = new StreamReader(resStream);
            var result = sr.ReadToEnd();
            sr.Close();
            resStream.Close();

            return result;
        }
    }
}
